package cn.laike.modules.dev.controller;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.laike.common.exception.RRException;
import cn.laike.common.utils.FileUtils;
import cn.laike.common.utils.PageUtils;
import cn.laike.common.utils.R;
import cn.laike.common.validator.ValidatorUtils;
import cn.laike.modules.dev.entity.ConfigEntity;
import cn.laike.modules.dev.service.ConfigService;
import cn.laike.modules.dev.utils.DevCacheUtils;
import cn.laike.modules.dev.utils.DevUtils;
import cn.laike.modules.sys.shiro.ShiroUtils;



/**
 * 小程序配置
 *
 * @author ziye
 * @email 524748907@qq.com
 * @date 2019-02-18 11:54:52
 */
@RestController
@RequestMapping("dev/config")
public class ConfigController {
    @Autowired
    private ConfigService configService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("dev:config:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = configService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info")
    @RequiresPermissions("dev:config:info")
    public R info(){
        ConfigEntity config = configService.getByUid(ShiroUtils.getUserId());
        if(config == null) {
        	config = new ConfigEntity();
        	config.setUid(ShiroUtils.getUserId());
        	config.setCreateTime(new Date());
        	config.setName(ShiroUtils.getUserEntity().getUsername());
        	config.setBg("bg.jpg");
        	configService.insert(config);
        }
        if(StringUtils.isEmpty(config.getBg())) {
        	config.setBg("bg.jpg");
        }
        return R.ok().put("config", config);
    }
    


    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("dev:config:save")
    public R save(@RequestBody ConfigEntity config){
        configService.insert(config);
        DevCacheUtils.del("config_"+ShiroUtils.getUserId());
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("dev:config:update")
    public R update(@RequestBody ConfigEntity config){
        ValidatorUtils.validateEntity(config);
        configService.updateAllColumnById(config);//全部更新
        DevCacheUtils.del("config_"+ShiroUtils.getUserId());
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("dev:config:delete")
    public R delete(@RequestBody Integer[] ids){
        configService.deleteBatchIds(Arrays.asList(ids));
        DevCacheUtils.del("config_"+ShiroUtils.getUserId());
        return R.ok();
    }
    
    
	@RequestMapping("/upload")
	public R upload(@RequestParam("picfile") MultipartFile picfile,HttpServletRequest request) throws Exception {
		if (picfile.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		String certName = "";
		String certFile = "";
		if(picfile != null && picfile.getOriginalFilename().length()>4){
			String productPath = "/opt/res_data/certificate/";
			//String productPath = "D:/opt/res_data/certificate/";
			FileUtils.createDirectory(productPath);
			String sname = picfile.getOriginalFilename();
			String fileType = sname.substring(sname.lastIndexOf("."));
			String fname  = "cert_user_"+ShiroUtils.getUserId()+fileType;
			File file = new File(productPath+fname);
			System.out.println("保存文件:"+productPath+fname);
			try {
				picfile.transferTo(file);
				certName = file.getName();
				certFile = file.getPath();
			} catch (Exception e) {
				System.out.println("上传文件失败:"+productPath+fname);
				e.printStackTrace();
			}
		}
		return R.ok().put("certName", certName).put("certFile", certFile);
	}
	
	@RequestMapping("/uploadbg")
	public R uploadbg(@RequestParam("picfile") MultipartFile picfile,HttpServletRequest request) throws Exception {
		if (picfile.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		String url = "";
		if(picfile != null && picfile.getOriginalFilename().length()>4){
			String picFilePath = DevUtils.getConfigResourceSavePath()+File.separator;
			FileUtils.createDirectory(picFilePath);
			String sname = picfile.getOriginalFilename();
			String fileType = sname.substring(sname.lastIndexOf("."));
			String fname  = "bg_"+ShiroUtils.getUserId()+fileType;
			File file = new File(picFilePath+fname);
			System.out.println("保存文件:"+picFilePath+fname);
			try {
				picfile.transferTo(file);
				url = file.getName();
			} catch (Exception e) {
				System.out.println("上传文件失败:"+picFilePath+fname);
				e.printStackTrace();
			}
		}
		return R.ok().put("url", url);
	}
	
	@RequestMapping("/uploadrecommend")
	public R uploadrecommend(@RequestParam("picfile") MultipartFile picfile,HttpServletRequest request) throws Exception {
		if (picfile.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		String url = "";
		if(picfile != null && picfile.getOriginalFilename().length()>4){
			String picFilePath = DevUtils.getConfigResourceSavePath()+File.separator;
			FileUtils.createDirectory(picFilePath);
			String sname = picfile.getOriginalFilename();
			String fileType = sname.substring(sname.lastIndexOf("."));
			String fname  = "recommend_"+ShiroUtils.getUserId()+fileType;
			File file = new File(picFilePath+fname);
			System.out.println("保存文件:"+picFilePath+fname);
			try {
				picfile.transferTo(file);
				url = file.getName();
			} catch (Exception e) {
				System.out.println("上传文件失败:"+picFilePath+fname);
				e.printStackTrace();
			}
		}
		return R.ok().put("url", url);
	}

}
